//
//  HomeRecommendGoodsListView.swift
//  HomeRecommendGoodsListView
//
//  Created by Ben on 2021/8/26.
//

import SwiftUI

struct HomeRecommendGoodsListView: View {
    
    @EnvironmentObject var homeVM: HomeViewModel
        
    var body: some View {
        
        GeometryReader { proxy in
            HStack(spacing: 0) {
                ForEach(homeVM.myChannelList) { tab in
                    FlowLayoutView(
                        list: DEFAULT_GOODSCARD_MODELS,
                        colums: 2,
                        showsIndicators: true,
                        spacing: 30
                    ) { goodsCardModel in
                        HomeRecommendGoodsCardView(goodsCardModel: goodsCardModel)

                    }
                    .padding(.bottom, 40)
                    .padding(.horizontal, 16)
                    .frame(width: SCREEN_WIDTH)
                }
            }
            .frame(alignment: .leading)
            .offset(x: -SCREEN_WIDTH * CGFloat(homeVM.homeRecommendCurrTabIndex), y: 0)
            .gesture(dragGesutre)
        }
        .frame(height: 1000)
        
        
    }
}

extension HomeRecommendGoodsListView {
    
    private var dragGesutre: some Gesture {
        DragGesture()
            
            .onEnded { endValue in
                
                var currTabIndex = homeVM.homeRecommendCurrTabIndex
                /// 拖动右滑，偏移量增加，显示 index 减少
                if endValue.translation.width > 50 {
                    currTabIndex -= 1
                }
                /// 拖动左滑，偏移量减少，显示 index 增加
                if endValue.translation.width < -50 {
                    currTabIndex += 1
                }
                /// 防止越界
                currTabIndex = max(min(currTabIndex, homeVM.myChannelList.count - 1), 0)
                homeVM.homeRecommendCurrTab = homeVM.myChannelList[currTabIndex]
                withAnimation(.spring()) {
                    homeVM.homeRecommendCurrTabIndex = currTabIndex
                }
            }
    }
}
